import 'package:flutter/material.dart';
import 'package:p_location/alarm/constant/alarm_http_url.dart';
import 'package:p_location/alarm/obj/obj_lack_num_detail.dart';
import 'package:p_location/alarm/res/alarm_area_item.dart';
import 'package:p_location/alarm/res/area/res_area_lack_num_detail.dart';
import 'package:p_location/alarm/utils/trace_judger.dart';
import 'package:p_location/common/res/common_res.dart';
import 'package:p_location/common/widget/no_result_widget.dart';
import 'package:p_location/common/widget/norm_item.dart';
import 'package:p_location/common/widget/split_title_view.dart';
import 'package:p_location/common/widget/tag_view.dart';
import 'package:p_location/common/widget/vertical_info_item.dart';
import 'package:p_location/map/res/search_person_detail.dart';
import 'package:p_location/net/dio_http_client.dart';
import 'package:p_location/net/net_constants.dart';
import 'package:p_location/net/net_listener_impl.dart';
import 'package:dio/dio.dart';
import 'package:p_location/utils/navigator_util.dart';
import 'package:p_location/utils/net/search_person_util.dart';
import 'package:p_location/utils/string_util.dart';
import 'package:intl/intl.dart';

//缺员报警

class PageAlarmAreaPersonLackDetail extends StatefulWidget {

  final AlarmAreaItem item;

  final int id;

  final bool isLack;

  final String info;

  //报警类型
  final String alarmTypeName;
  //报警状态
  final String status;

  final String time;

  PageAlarmAreaPersonLackDetail(this.item,this.id, this.isLack, this.info, this.time,this.alarmTypeName,this.status);

  @override
  _PageAlarmAreaPersonLackDetailState createState() =>
      _PageAlarmAreaPersonLackDetailState();
}

class _PageAlarmAreaPersonLackDetailState
    extends State<PageAlarmAreaPersonLackDetail> {
  String errMsg = "";
  bool isLoading = true;
  ObjLackNumDetail oneKeyDetail;

  SearchPersonDetail fullDetail;
  DateFormat formatter = new DateFormat('yyyy-MM-dd HH:mm:ss');

  @override
  void initState() {
    super.initState();
    if (widget.item != null && StringUtil.isNotEmpty(widget.item.sn)) {
      _getFullInfoBySn(widget.item.sn);
    } else {
      _getDetail();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          elevation: 0,
          brightness: Brightness.dark,
          title: Text("报警详情"),
          centerTitle: true,
          leading: IconButton(
              tooltip: '返回',
              icon: Icon(Icons.arrow_back_ios, color: Colors.white),
              onPressed: () {
                Navigator.of(context).pop();
              }),
        ),
        body: isLoading
            ? _loadingView
            : StringUtil.isEmpty(errMsg)
                ? _contentView
                : _exceptionView);
  }

  get _loadingView => Center(child: CircularProgressIndicator());

  get _contentView => ListView(
        children: [
          VerticalInfoItem("事件", widget.info),
          VerticalInfoItem("报警类型", widget.alarmTypeName),
          VerticalInfoItem("报警时间", widget.time),
          IntrinsicHeight(
            child:
            Row(
              mainAxisSize:MainAxisSize.max,
              children: [
                Expanded(child: VerticalInfoItem("报警状态", widget.status),flex: 2,),
                Expanded(child:
                  Container(
                      decoration: BoxDecoration(
                          color: Colors.white,
                          border:
                          Border(bottom: BorderSide(color: Colors.grey, width: 0.4))),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                   children: [
                    Offstage(
                      offstage: widget.status != '报警中' || TraceJudger.isHide(widget.alarmTypeName),
                      child: TagView(
                        "追踪",
                        paddingLeft: 15,
                        paddingRight: 15,
                        paddingTop: 1,
                        paddingBottom: 1,
                        radius: 5,
                        strokeColor: Color.fromARGB(255, 56, 160, 253),
                        textColor: Color.fromARGB(255, 56, 160, 253),
                        fillColor: Colors.white,
                        onPress: (){
                          if (fullDetail == null) {
                            fullDetail = SearchPersonDetail();
                            fullDetail.id = widget.item.id;
                            fullDetail.name = widget.item.personNameOrAreaName;
                            fullDetail.sn = widget.item.sn;
                            fullDetail.typeName = widget.item.typeName;
                          }

                          NavigatorUtil.jumpToLocationPageWithTarget(
                              context, fullDetail);
                        },
                      ),
                    )
                  ],
                )
                ),),
              ],
            ),
          ),
          VerticalInfoItem("报警区间", oneKeyDetail.areaName),
          widget.isLack
              ? VerticalInfoItem("描述",
                  '缺少人数：${oneKeyDetail.lackNum}人 (区域小于${oneKeyDetail.settingNum}人产生报警)')
              : VerticalInfoItem("描述",
                  '超出人数：${oneKeyDetail.overNum}人 (区域大于${oneKeyDetail.settingNum}人产生报警)'),
          SplitTitleView("报警时刻区域内人员"),
          _historyPersonView,
          VerticalInfoItem("当前人数", '${oneKeyDetail.currentNum}人'),
          SplitTitleView("当前区域内人员"),
          _currentPersonView
        ],
      );

  get _exceptionView => NoResultWidget('images/img_no_accident.png', errMsg);

  get _currentPersonView => Column(
        children: getCurrentPersonWidgets(),
      );

  get _historyPersonView => Column(
    children: getHistoryPersonWidgets(),
  );

  getCurrentPersonWidgets() {
    List<Widget> widgetList = [];
    if (oneKeyDetail.currentPersons != null &&
        oneKeyDetail.currentPersons.length > 0) {
      oneKeyDetail.currentPersons.forEach((element) {
        widgetList.add(NormItem(element.name, ""));
      });
    }
    return widgetList;
  }

  getHistoryPersonWidgets() {
    List<Widget> widgetList = [];
    if (oneKeyDetail.inDetails != null &&
        oneKeyDetail.inDetails.length > 0) {
      oneKeyDetail.inDetails.forEach((element) {
        widgetList.add(NormItem(element.personName, formatter.format(DateTime.fromMillisecondsSinceEpoch(element.inTime))));
      });
    }
    return widgetList;
  }

  _getDetail() async {
    Map<String, dynamic> params = {};
    params["id"] = widget.id;
    await DioHttpClient.requestPost(
        context,
        widget.isLack
            ? AlarmHttpUrl.ALARM_LACK_DETAIL_URL
            : AlarmHttpUrl.ALARM_OVER_NUM_DETAIL_URL,
        params,
        NetListenerImpl(onSuccess, onError),
        contentType: NetConstants.POST_TYPE_FORM);
  }

  void onSuccess(Response response) {
    setState(() {
      if (response != null && response.data != null) {
        ResAreaLackNumDetail res = ResAreaLackNumDetail.fromJson(response.data);
        if (res != null && res.data != null) {
          oneKeyDetail = res.data;
        }
        isLoading = false;
      }
    });
  }

  void onError(CommonRes errorRes) {
    setState(() {
      errMsg = errorRes.msg ?? "请求异常";
      isLoading = false;
    });
  }

  _getFullInfoBySn(String keyword) {
    SearchPersonUtil searchPersonUtil =
    SearchPersonUtil(keyword, (List<SearchPersonDetail> _detailList) {
      if (_detailList != null && _detailList.length > 0) {
        SearchPersonDetail searchPersonDetail = _detailList[0];
        if (searchPersonDetail != null) {
          fullDetail = searchPersonDetail;
        }
      }
      _getDetail();
    }, () {
      _getDetail();
    });
    searchPersonUtil.requestSearchPerson(context);
  }
}
